package org.client.iot.ui.project;

import static android.Manifest.permission.*;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothProfile;
import android.content.Intent;

import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bumptech.glide.Glide;
import com.lucky.base.network.NetworkApi;
import com.lucky.base.network.observer.BaseObserver;
import com.lucky.utils.log.LogUtils;

import org.client.iot.LauncherApplication;
import org.client.iot.R;
import org.client.iot.ble.BleTemplate;
import org.client.iot.constant.GlobeDataManager;
import org.client.iot.databinding.ActivityProjectManagerBinding;
import org.client.iot.domain.DeviceDto;
import org.client.iot.domain.ProjectDto;
import org.client.iot.http.ApiService;
import org.client.iot.http.BaseRes;
import org.client.iot.ui.ble.BindBleActivity;
import org.client.iot.ui.device.adapter.DevListAdapter;
import org.client.iot.ui.project.fragment.ProjectHomeFragment;
import org.client.iot.util.MMKVUtils;
import org.client.iot.util.PermissionManager;
import org.tzw.template.base.BaseActivity;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import io.reactivex.Observable;

public class ProjectManagerActivity extends BaseActivity<ActivityProjectManagerBinding> {
    private DevListAdapter devListAdapter;
    private String projectName;
    private int projectId;
    private final int pageSize = 10; // 数据量
    private int pageNum = 1; // 页码
    private int total;

    @Override
    protected void initData() {
        devListAdapter = new DevListAdapter(this, new ArrayList<>());
        projectName = getIntent().getStringExtra("projectName");
        projectId = getIntent().getIntExtra("projectId", 0);
    }

    @Override
    protected void initView() {
        setSupportActionBar(mRoot.toolbarDeviceManager);
        mRoot.textViewTitle.setText(projectName);
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mRoot.recDevList.setLayoutManager(manager);
        mRoot.recDevList.setAdapter(devListAdapter);
        mRoot.recDevList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        getShortList(pageNum, pageSize);

    }

    @Override
    protected void onResume() {
        super.onResume();
        updateConnectImage(BleTemplate.getInstance().getConnectStatus());
    }

    @Override
    protected void initListener() {
        mRoot.imgBack.setOnClickListener(v -> {
            finish();
        });
        mRoot.btnAddDev.setOnClickListener(v -> {
            PermissionManager.checkPermission(this, new PermissionManager.AcceptPermissionListener() {
                @Override
                public void onSuccess() {
                    Intent intent = new Intent(ProjectManagerActivity.this, BindBleActivity.class);
                    intent.putExtra("projectName", projectName);
                    intent.putExtra("projectId", projectId);
                    startActivity(intent);
                }

                @Override
                public void onFail() {
                    showToastShort(getString(R.string.permission_error));
                }

                @Override
                public void onError(Throwable e) {
                    showToastShort(StrUtil.format(getString(R.string.permission_error)+":{}",e.getCause()));
                }
            },ACCESS_FINE_LOCATION,CHANGE_WIFI_STATE,ACCESS_WIFI_STATE,ACCESS_COARSE_LOCATION,CHANGE_NETWORK_STATE);
        });
        devListAdapter.setOnItemClickListener((adapter, view, position) -> {
            //@TODO 设置局域网IP-目前先写死---start
//            MMKVUtils.getInstance().put("ip", "192.168.5.1");
//            MMKVUtils.getInstance().put("port", "8000");
            MMKVUtils.getInstance().put("ip", "http://701bf6d9.r8.cpolar.top");
            MMKVUtils.getInstance().put("port", "0");
            LauncherApplication.initNetWork(getApplication());
            //@TODO 设置局域网IP-目前先写死---end
            Intent intent = new Intent(this, ProjectOptionActivity.class);
            intent.putExtra("devName", devListAdapter.getData().get(position).getDeviceName());
            startActivity(intent);
        });
        GlobeDataManager.bluetoothProfileLiveData.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer status) {
                updateConnectImage(status);
            }
        });
        //上拉加载更多
        devListAdapter.getLoadMoreModule().setPreLoadNumber(1);
        devListAdapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
        devListAdapter.getLoadMoreModule().setOnLoadMoreListener(() -> {
            if (total <= pageNum * pageSize) {
                devListAdapter.getLoadMoreModule().loadMoreEnd();
                return;
            }
            getShortList(pageNum + 1, pageSize);

        });

    }

    private void updateConnectImage(Integer status) {
        if (status == BluetoothProfile.STATE_CONNECTED) {
            Glide.with(this).load(R.mipmap.ico_bluetooth)
                    .into(mRoot.imgConnect);
        } else {
            Glide.with(this).load(R.mipmap.ico_bluetooth_unconnect)
                    .into(mRoot.imgConnect);
        }
    }

    // 获取设备列表
    private void getShortList(int page, int pageSize) {
        String token = "Bearer " + MMKVUtils.getInstance().get("token", "");
        Observable<BaseRes<DeviceDto>> compose = NetworkApi.createService(ApiService.class, "")
                .getShortList(token, page, pageSize, "181", null, "")
                .compose(NetworkApi.applySchedulers(new BaseObserver<BaseRes<DeviceDto>>() {
                    @SuppressLint({"CheckResult", "NotifyDataSetChanged"})
                    @Override
                    public void onSuccess(BaseRes<DeviceDto> req) {
                        if (req == null) {
                            return;
                        }
                        runOnUiThread(() -> {
                            LogUtils.i("获取设备列表req==", req.toString());
                            total = req.getTotal();
                            List<DeviceDto> reqRows = req.getRows();
                            if(CollUtil.isEmpty(reqRows)){
                                return;
                            }
                            devListAdapter.addData(req.getRows());
                            pageNum = page;
                            if (total <= pageNum * pageSize) {
                                devListAdapter.getLoadMoreModule().loadMoreEnd();
                            }else {
                                devListAdapter.getLoadMoreModule().loadMoreComplete();
                            }


                        });
                    }

                    @SuppressLint("CheckResult")
                    @Override
                    public void onFailure(Throwable e) {
                        runOnUiThread(() -> {
                            showToastLong(e.getMessage());
                            if (page > 1) {
                                pageNum--;
                            }
                        });
                    }

                }));
    }


}